package org.abratuhi.kvngroupware.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.abratuhi.kvngroupware.client.KVNGroupwareClient;


public class C_Client implements Runnable{
	/**/
	public Socket clientSocket;
	public boolean runOK = false;
	public Thread thread;
	
	String host;
	Integer port;
	
	KVNGroupwareClient kvnclient;
	

	/**/
	public C_Client(KVNGroupwareClient kvnclient, String host, Integer port){
		this.kvnclient = kvnclient;
		this.host = host;
		this.port = port;
	}
	
	String getHost(){
		return this.host;
	}
	Integer getPort(){
		return this.port;
	}

	/**/
	public void sendMessage(Message msg){
		if (clientSocket != null && !clientSocket.isClosed()){
		try {
			new DataOutputStream(clientSocket.getOutputStream()).writeUTF(msg.toString());
		} catch (IOException e) {
			e.printStackTrace();
			stop();
		}
		}
	}
	public Message receiveMessage(){
		String strMsg = null;
		if(clientSocket != null && !clientSocket.isClosed()){
		try {
			strMsg = new DataInputStream(clientSocket.getInputStream()).readUTF();
			if(strMsg != null && strMsg != ""){
				return Message.fromMessage(strMsg);
			}
			else{
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			stop();
		}
		}
		return null;
	}

	/**/
	public void run(){
		System.out.println("C_Client:\tstarted.");
		while(getRunOK()){
			try {
				//
				Message message = receiveMessage();

				//msg_incoming.add(message);
				if(message!=null) kvnclient.proceedMessage(message);
				
				// sleep
				Thread.sleep(100);
			} catch (InterruptedException e) {
				System.out.println("C_Client:\tinterrupted.");
				//setRunOK(false);
				break;
			}
		}
		System.out.println("C_Client:\tstopped.");
		return;
	}
	
	public void start(){
		this.connect();
		this.setRunOK(true);
		this.thread = new Thread(this);
		this.thread.start();
	}
	
	public void stop(){
		this.setRunOK(false);
		this.thread.interrupt();
		this.disconnect();
	}
	
	public void connect(){
		try {
			clientSocket = new Socket(getHost(), getPort());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disconnect(){
		try {
			clientSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**/

	public synchronized boolean getRunOK(){
		return this.runOK;
	}

	public synchronized void setRunOK(boolean run){
		this.runOK = run;
	}

	public synchronized void switchRunOK(){
		this.runOK = (this.runOK == true)? false:true;
	}

}
